package com.hzit.auth.filter;

import com.hzit.auth.security.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */

public class TokenAuthFilter extends BasicAuthenticationFilter {

	private TokenManager tokenManager;
	private RedisTemplate redisTemplate;

	public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
		super(authenticationManager);
		this.tokenManager = tokenManager;
		this.redisTemplate = redisTemplate;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
		//1. 得到token值
		String token = request.getHeader("token");
		if(token != null){
			//2. 通过jwt传入token，解析得到用户名
			String username = tokenManager.getUserInfoFromToken(token);

			//3. 通过用户名得到权限列表
			List<String> permissionValueList = (List<String>)redisTemplate.opsForValue().get(username);
			//4. 权限列表为List<GrantedAuthority>
			List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(permissionValueList.toString().replace("[", "").replace("]", ""));
			//5. 得到
			UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,token,grantedAuthorities);
			//6. 将UsernamePasswordAuthenticationToken设置到当前认证的上下文中，方便下次得到
			if(authenticationToken != null) {
				SecurityContextHolder.getContext().setAuthentication(authenticationToken);
			}

		}
		//7. 调用下一个过滤器
		chain.doFilter(request,response);

	}
}
